<template>
  <view class="buddyList">
    <view class="search-view">
      <u-search :show-action='false' placeholder="搜索" v-model="search" @search="searchFn"></u-search>
    </view>
    <view class="structure">
      <view class="structure-item" :style="{
				 color:index !== structures.length-1 ? '#0086FE':'#888'
			 }" v-for="(structure,index) in structures"
            :key="structure"
            @click="changeStrcure(index)">
        {{ structure }}
        <template v-if="index !== structures.length-1">
          >
        </template>
      </view>
    </view>

    <view class="contact-list">
      <view class="department" v-if="department.length">
        <view class="department-item" :key="it.ID" v-for="(it,index) in department"
              @click="departmentClickHandle(it,index)">
          {{ it.name }}
          <view class="pull-right">
            <u-icon style="margin-right: 20rpx;" name="list"></u-icon>
            下级
          </view>
        </view>
      </view>
      <view class="personnel">

        <u-checkbox-group :max="max" :value="selectContact" width="100%" shape="circle" :wrap="true">
          <template v-for="it in personnel">
            <u-checkbox v-model="it.checked"
                        :key="it.id"
                        warp
                        :name="it.id" @change="checkboxChange(it,$event)">
              <view class="personnel-item">
                <image class="avatar" src="@/static/images/avatar.png"></image>
                <view class="user-info">
                  <view class="userName">{{ it.name }}</view>
                  <view class="depName">{{ it.depName }}</view>
                </view>
              </view>
            </u-checkbox>

          </template>
        </u-checkbox-group>
      </view>
    </view>

    <view class="float-bar">
      <view class="contact-count">
        <view @click="showPupUp" v-if="selectContact.length"> {{ selectText }}
          <u-icon name="arrow-up"></u-icon>
        </view>
      </view>
      <view class="confirm-button">
        <u-button ripple type="primary" @click="confirmFn">确定({{ selectContact.length }})</u-button>
      </view>
    </view>

    <uni-popup ref="popup" type="bottom">
      <view class="uni-share-title">
        <text class="uni-share-title-text">已选择的联系人</text>
      </view>
      <scroll-view scroll-y class="personnel" style="max-height: 40vh">
        <template v-for="it in selectContact">
          <u-checkbox warp v-model="it.checked" :name="it.id"
                      @change="checkboxChange(it,$event)">
            <view class="personnel-item">
              <image class="avatar" src="@/static/images/avatar.png"></image>
              <view class="user-info">
                <view class="userName">{{ it.name }}</view>
                <view class="depName">{{ it.depName }}</view>
              </view>
            </view>
          </u-checkbox>
        </template>
      </scroll-view>
    </uni-popup>
  </view>
</template>

<script>
import UButton from "../../uview-ui/components/u-button/u-button";
import UIcon from "../../uview-ui/components/u-icon/u-icon";
import {
  toTreeData
} from "../../utils/util";
import UCheckboxGroup from "../../uview-ui/components/u-checkbox-group/u-checkbox-group";
import UCheckbox from "../../uview-ui/components/u-checkbox/u-checkbox";
import USearch from "../../uview-ui/components/u-search/u-search";

export default {
  components: {
    USearch,
    UCheckbox,
    UCheckboxGroup,
    UIcon,
    UButton
  },
  data() {
    return {
      search: '',
      treeData: null,
      pageIndex: [ 0 ],
      personnel: [],
      selectContactMap: new Map(),
      selectContact: [],
      selModel: 0
    }
  },
  watch: {
    'selectContact.length'(val) {
      if (val === 0) {
        this.$refs.popup.close()
      }
      this.initChecked()
    }
  },
  computed: {
    max() {
      return this.selModel === '0' ? 1 : 999
    },
    selectText() {
      if (this.selectContact.length) {
        return `已选择${ this.selectContact.length }人`
      } else {
        return ''
      }
    },
    currentPage() {
      let currentPage = this.treeData;
      if (currentPage && currentPage.children) {
        this.pageIndex.forEach(e => {
          if (e === 999){
            currentPage = []
          }else{
            currentPage = currentPage.children[e]
          }
        })
      }
      return currentPage
    },
    department() {
      if (this.currentPage && this.pageIndex[this.pageIndex.length-1] !== 999) {
        return this.currentPage.children
      } else {
        return []
      }
    },
    structures() {
      let structure = []
      let currentPage = this.treeData;
      if (currentPage && currentPage.children) {
        this.pageIndex.forEach(e => {
          if (e === 999){
            structure.push('搜索')
          }else{
            currentPage = currentPage.children[e]
            structure.push(currentPage.name)
          }
        })
      }
      return structure
    }
  },
  methods: {
    confirmFn() {
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('sendContactData', {
        data: this.selectContact
      });
      uni.navigateBack()
    },
    initChecked() {
      let ids = this.selectContact.map(e => e.id)
      this.personnel = this.personnel.map(e => {
        e.checked = ids.includes(e.id)
        return e
      })
    },
    async searchFn(value) {
      uni.showLoading({
        mask: true,
        title: '搜索中'
      })
      if (this.pageIndex.indexOf(999) === -1){
        this.pageIndex= [0,999]
      }
      let res = await this.api.getOrgTree_queryuser({ queryUser: value })
      this.personnel = res.data
      this.initChecked()
      uni.hideLoading()
    },
    showPupUp() {
      this.$refs.popup.open()
    },
    changeStrcure(index) {
      if (index === this.pageIndex.length - 1) return
      this.pageIndex.splice(index + 1, this.pageIndex.length - index)
      this.getPersonnel()
    },
    checkboxChange(data, e) {
      if (this.selectContactMap.has(e.name)) {
        this.selectContactMap.get(e.name).checked = false
        this.selectContactMap.delete(e.name)
      } else {
        this.selectContactMap.set(e.name, data)
      }
      this.selectContact = Array.from(this.selectContactMap).map(e => e[1])
    },
    departmentClickHandle(data, index) {
      this.pageIndex.push(index)
      this.getPersonnel()
    },
    async getPersonnel() {
      this.personnel = [];
      let data = this.currentPage
      if (!data) return;
      uni.showLoading({
        mask: true,
        title: '加载中'
      })
      let res;
      if (data.nowDep) {
        res = await this.api.getOrgTree_user(data.nowDep)
      } else {
        res = await this.api.getOrgTree_user(data.id)
      }
      this.personnel = res.data;
      this.initChecked()
      uni.hideLoading()
    },
    async fetchData(userIds) {
      uni.showLoading({
        mask: true,
        title: '加载中'
      })
      if (userIds) {
        userIds = userIds.split(' ').join(';');
        let res = await this.api.getUserByIds({ userIds })

        this.selectContact = res.data.map(e => {
          e.checked = true
          this.selectContactMap.set(e.id, e)
          return e
        })
        console.log(this.selectContact);
      }

      let data = await this.api.getOrgTree({});
      this.treeData = toTreeData(data.data, {
        id: 'id',
        parendId: 'pId',
        name: 'name',
        rootId: ''
      })
      await this.getPersonnel()
      uni.hideLoading()
    }
  },
  onLoad(options) {
    this.selModel = options.selModel
    this.idField = options.idField

    this.fetchData(options.userIds)
  }
}
</script>

<style lang="less" scoped>
.buddyList {
  background: #FFF;
  display: flex;
  flex-direction: column;
  height: 100vh;
  // padding: 20rpx 0 120rpx;
  /* #ifdef H5 */
  height: calc(100vh - 88rpx);

  /* #endif */

  .search-view {
    padding: 20rpx;
  }

  .structure {
    padding: 20rpx;
    display: flex;
    flex-wrap: wrap;
    border-bottom: 20rpx solid #EEE;
    line-height: 1.8;

  }

  .contact-list {

    flex: 1;
    overflow: scroll;

    .department {
      padding: 0 20rpx;
      border-bottom: 20rpx solid #eee;

      .department-item {
        font-size: 30rpx;
        border-bottom: 1px solid #eee;
        padding: 26rpx 0;
        position: relative;

        .pull-right {
          right: 20rpx;
          top: 50%;
          transform: translateY(-50%);
          position: absolute;
          color: #0086FE;
          border-left: 1rpx solid #eee;
          padding-left: 20rpx;
        }
      }
    }
  }

  .personnel {
    padding: 0 20rpx;

    .u-checkbox-group {
      width: 100%;
    }

    .personnel-item {
      width: 100%;
      display: flex;
      align-items: center;

      .user-info {
        flex: 1;
        border-bottom: 2rpx solid #eee;
        padding: 10rpx 0;
        line-height: 1.6;
        color: #333;
      }

      .avatar {
        width: 90rpx;
        height: 90rpx;
        vertical-align: top;
        margin-right: 20rpx;
      }


    }
  }

  .float-bar {
    border-top: 1px solid #eee;
    padding: 20rpx 20rpx calc(20rpx + var(--window-bottom)) 20rpx;
    align-items: center;
    display: flex;
    background: #FFF;
    width: 100%;
    justify-content: space-between;

    .contact-count {
      color: #0086FE;
    }
  }

  .uni-share-title {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
    align-items: center;
    justify-content: center;
    height: 40px;
    border-bottom: 1px solid #eee;
  }

  .uni-share-title-text {
    font-size: 14px;
    color: #666;
  }
}
</style>
